package cn.credit.loan.shiro;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.credit.loan.entity.User;
import cn.credit.loan.service.user.UserService;

/**
 * 用户自定义Reaml类
 * @author
 *
 */
public class UserReaml extends AuthorizingRealm {

	@Autowired
	private UserService userService;

	// 设置realm的名称
	@Override
	public void setName(String name) {
		super.setName("userRealm");
	}

	/**
	 * 认证登录
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//
		String userphone = (String) token.getPrincipal();
		// 第二步：根据用户输入的userName从数据库查询
		User user = null;
		try {
			user = userService.userlogin(userphone);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 如果查询不到返回null
		if (user == null) {
			return null;
		}
		// 从数据库查询到密码
		String password = user.getUserPassword();
		// 将User设置simpleAuthenticationInfo
		SimpleAuthenticationInfo simpleAuthenticationInfo=null;
		try {
			simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, DigestUtils.md5Hex(password),
					getName());
			/*SimpleAuthenticationInfo(
					user, //用户
					password, //密码
	                ByteSource.Util.bytes(userphone), //散列
	                getName() //realm name 
			);*/	
			/*simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, password,this.getName());*/
		} catch (Exception e) {
			e.printStackTrace();
		}
		return simpleAuthenticationInfo;
	}

	/**
	 * 权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		return null;
	}

}
